﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.AttributeFile;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;

namespace DFGK_WMS.WebAPI.Controllers.移库管理
{
    /// <summary>
    /// 移库单
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TransferBinOrderModelController : ControllerBase
    {
        public TransferBinOrderModelController(ITTransferBinOrderRepository tTransferBinOrderRepository, ITCompanyRepository tCompanyRepository, ITTransferBinOrderDetailRepository tTransferBinOrderDetailRepository, ITInventoryRepository tInventoryRepository, IUserRepository userRepository, ITTransferBinOrderDetailRepository tTransferBin)
        {
            TTransferBinOrderRepository = tTransferBinOrderRepository;
            TCompanyRepository = tCompanyRepository;
            TTransferBinOrderDetailRepository = tTransferBinOrderDetailRepository;
            TInventoryRepository = tInventoryRepository;
            UserRepository = userRepository;
            TTransferBin = tTransferBin;
        }

        public ITTransferBinOrderRepository TTransferBinOrderRepository { get; }
        public ITCompanyRepository TCompanyRepository { get; }

        public ITTransferBinOrderDetailRepository TTransferBinOrderDetailRepository { get; }
        public ITInventoryRepository TInventoryRepository { get; }
        public IUserRepository UserRepository { get; }
        public ITTransferBinOrderDetailRepository TTransferBin { get; }

        #region 移库单管理

        /// <summary>
        /// 提交数据 （增加/修改/删除 ）
        /// </summary>
        /// <param name="transferBinOrderModel"></param>
        /// <returns></returns>
        [HttpPost]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult SubmitTransferBinOrderData(TTransferBinOrderDTO transferBinOrder)
        {
            var IsOk = TTransferBinOrderRepository.SubmitTransferBinOrderData(transferBinOrder);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "保存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "保存失败！", "500"));
        }

        /// <summary>
        /// 查询全部移库单显示
        /// </summary>
        /// <param name="ordersn"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="companyId"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTransferBinOrderList(string? ordersn, DateTime? startTime, DateTime? endTime, int? companyId, int? status, int pageIndex = 1, int pageSize = 10)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            var list = TTransferBinOrderRepository.GetTransferBinOrderList(ordersn, startTime, endTime, companyId, status, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
        /// <summary>
        /// 移库单显示
        /// </summary>
        /// <param name="ordersn"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="companyId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetExcel(string? ordersn, DateTime? startTime, DateTime? endTime, int? companyId, int? status)
        {
          var list=  TTransferBinOrderRepository.GetExcel(ordersn, startTime, endTime, companyId, status);
            return Ok(list);
            
        }
        /// <summary>
        /// 根据Id获取移库单对象
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTransferBinOrderById(int tid)
        {
            if (tid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var tran = TTransferBinOrderRepository.GetTransferBinOrderById(tid);
            if (tran != null)
            {
                return Ok(BaseResult.Result(tran, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }

        /// <summary>
        /// 移库单删除
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelTransferBinOrder(int tid)
        {
            if (tid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = TTransferBinOrderRepository.DelTransferBinOrder(tid);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }

        /// <summary>
        /// 生成移库单编号
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GenerateNum()
        {
            DateTime currentDateTime = DateTime.Now;
            string year = currentDateTime.ToString("yyyy");
            string month = currentDateTime.ToString("MM");
            string day = currentDateTime.ToString("dd");
            string hour = currentDateTime.ToString("HH");
            string minute = currentDateTime.ToString("mm");
            string second = currentDateTime.ToString("ss");
            string randomNumber = GenerateRandomNumber(1000000, 9999999).ToString();

            string dateTimeRandomNumber = $"{year}{month}{day}{hour}{minute}{second}{randomNumber}";

            return Ok(BaseResult.Result(dateTimeRandomNumber, "生成单号！", "200"));
        }

        /// <summary>
        /// 获取所有公司类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetEmStationType()
        {
            var list = TCompanyRepository.GetTcompanyList().Select(c => new
            {
                c.Id,
                c.Name,
                c.Code
            }).ToList();

            return Ok(list);
        }



        /// <summary>
        /// 获取物料库存库位
        /// </summary>
        /// <param name="MaterialId">物料Id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInventoryCellData(int MaterialId)
        {
            if(MaterialId<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var list = TInventoryRepository.GetInventoryList().Where(i => i.MaterialId == MaterialId).ToList();
            if (list.Count <= 0)
            {
                return Ok(BaseResult.Result(list, "查询失败!", "200", 0));
            }
            return Ok(BaseResult.Result(list.Select(t => new
            {
                QId = t.Id,
                QLocationId = t.LocationId,
                QLocationCode = t.LocationCode,
                QLocationName = t.LocationName,
                QWhId = t.WarehouseId,
                QWhName = t.WarehouseName,
                QWarehouseCode = t.WarehouseCode,
                QAreaId = t.AreaId,
                QAreaName = t.AreaName,
                AvailableQTY = t.AvailableQty,

            }).ToList(), "查询成功！", "200", 0));
        }

        /// <summary>
        /// 获取移库的可用空仓位
        /// </summary>
        /// <param name="fromLocationId"></param>
        /// <param name="isPriorityFilling"></param>
        /// <param name="filterType"></param>
        /// <param name="toLogicalPartCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTransferBinedCellSelectData(string? toLogicalPartCode, int FromLocationId, bool isPriorityFilling = false, int filterType = 1)
        {
            var list = TTransferBinOrderRepository.GetEnabledCellListByFromLocationId(toLogicalPartCode, FromLocationId, isPriorityFilling, filterType);
            if (list == null)
            {
                return Ok(BaseResult.Result(null, "查询失败!", "500", 0));
            }
            return Ok(BaseResult.Result(list.Select(t => new
            {
                HId = t.Id,
                HName = t.Name,
                HCode = t.Code,
                HWhId = t.WhId,
                HWhName = t.WhName,
                HAreaId = t.AreaId,
                HAreaName = t.AreaName,


            }).ToList(), "查询成功！", "200", 0));
        }

        /// <summary>
        /// 查看移库单的详细信息
        /// </summary>
        /// <param name="Id">移库单id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SelectTransferBinOrder(int Id)
        {
            if (Id > 0)
            {
                var data = TTransferBinOrderRepository.SelectTransferBinOrder(Id);
                return Ok(BaseResult.Result(data, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "Id有误", "500"));
        }

        /// <summary>
        /// 执行移库单
        /// </summary>
        /// <param name="Id">移库单Id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult UpdateTransState(int Id)
        {
            if (Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool isOk = false;
            var tran = TTransferBinOrderRepository.GetTransferBinOrderById(Id);
            if (tran != null)
            {
                tran.Status = 3;
                isOk = TTransferBinOrderRepository.UpdateTransferBinOrder(tran);
            }
            if (isOk)
            {
                return Ok(BaseResult.Result(true, "执行成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "执行失败！", "500"));
        }

        /// <summary>
        /// 提交移库单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SubmitTranState(SubmitTranDTO submitTranDTO)
        {
            var isok = TTransferBinOrderRepository.SubmitTranState(submitTranDTO);
            if (isok)
            {
                return Ok(BaseResult.Result(true, "提交成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "提交失败！", "500"));
        }

        #endregion

        #region 移库单明细管理

        /// <summary>
        /// 删除移库单明细
        /// </summary>
        /// <param name="Id">移库单明细id</param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelTransferBinOrderDetails(int Id)
        {
            if (Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = TTransferBinOrderDetailRepository.DelTransferBinOrderDetails(Id);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));

        }
        /// <summary>
        /// 显示当前移库单的明细
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTransferBinOrderDetailsList(int orderId, int pageIndex=1, int pageSize=10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            var list = TTransferBinOrderDetailRepository.GetTransferBinOrderDetailsList(orderId, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
        /// <summary>
        /// 修改移库单明细物料信息
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        [HttpPut]

        public IActionResult UpdateTransferBinOrderDetails(TTransferBinOrderDetail t)
        {

            bool IsOK = TTransferBinOrderDetailRepository.UpdateTransferBinOrderDetails(t);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "修改成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败！", "500"));
        }
        /// <summary>
        /// 删除多条移库明细下物料信息数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DeleteTransferBinOrderDetails(List<int?> ids)
        {
            if (ids==null)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = TTransferBinOrderRepository.DeleteTransferBinOrderDetails(ids);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }
        /// <summary>
        /// 物料分类信息
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        [HttpGet]
       public IActionResult GetMaterialHierarchy(int? typeId)
        {
           var a= TTransferBin.GetMaterialHierarchy(typeId);
            return Ok(a);
        }
        /// <summary>
        /// 查询物料信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterials(string? name)
        {
            var list= TTransferBin.GetMaterials(name);
            return Ok(list);
        }
        /// <summary>
        /// 根据物料分类查询物料
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetParentTMaterial(int id)
        {
            var list = TTransferBin.GetParentTMaterial(id);
            return Ok(list);
        }
        /// <summary>
        /// 仓位信息下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet]
       public IActionResult GetCells()
        {
            var list=TTransferBin.GetCells();
            return Ok(list);    
        }

 
        #endregion
        private static int GenerateRandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }

        /// <summary>
        /// 移库任务下传
        /// </summary>
        /// <returns></returns>       
        [HttpPost]
        public IActionResult TransferTaskDownload(List<TransferSigles> transferSiglesList)
        {
            string message = "";
            bool IsOK = TTransferBinOrderRepository.TransferTaskDownload(transferSiglesList, out message);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "添加成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！" + message, "500"));
        }

        /// <summary>
        /// 移库单回传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BackTransferSigles()
        {
            var list=TTransferBinOrderRepository.BackTransferSigles();
            if(list!=null)
            {
                return Ok(BaseResult.Result(list, "获取成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "获取成功！", "500"));
        }


        /// <summary>
        /// 回传MES接口
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PostTransferBin(MESTransferBinDto dto)
        {
            if (dto == null)
            {
                return Ok(BaseResult.Result(false, "请求参数有误", "500"));
            }
            var IsOk = await TTransferBinOrderRepository.PostTransferBin(dto);
            if (IsOk)
            {
                return Ok(BaseResult.Result(true, "回传成功", "200"));
            }
            return Ok(BaseResult.Result(false, "回传失败", "500"));
        }
    }
}
